package com.wf.course.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.utils.page.PageBean;
import com.utils.security.EncryptionHelper;
import com.utils.security.UUIDGenerator;
import com.wf.course.dao.IUserMapper;
import com.wf.course.model.log.LoginLogs;
import com.wf.course.model.user.Role;
import com.wf.course.model.user.User;
import com.wf.course.model.user.UserRoleRelation;
import com.wf.course.service.IUserService;

@Service
@Transactional(rollbackFor=Exception.class)
public class IUserServiceImpl implements IUserService{

	@Autowired
	private IUserMapper iUserMapper;
	
	public User login(String userName, String password) {
		//通过用户名获取用户信息
		User user = iUserMapper.getById_Name_Telephone(userName, 2);
		//如果查询到用户并且密码正确 ,返回用户对象, 否则返回null
		if(user != null){
			if(user.getPassword().equals(EncryptionHelper.encrypt(password, user.getSalt())))
				return user;
			
			// 密码错误
			user.setPassword(null);
			return user;
		}
		
		return user;
	}

	public Integer addUser(User user) {
		return iUserMapper.addUser(user);
	}

	public User getById(Integer id) {
		return iUserMapper.getById_Name_Telephone(id.toString(), 1);
	}

	public Boolean updatePassword(Integer id, String password) {
		return iUserMapper.updatePassword(id , password);
	}
	
	
	//////////////////用户管理/////////////////////////////
	
	/**
	 * 首页列表
	 * @param pageBean
	 */
	@Override
	public void indexInfo(PageBean<User> pageBean) {
		pageBean.setResults(this.iUserMapper.queryList(pageBean));
		pageBean.setTotalCount(this.iUserMapper.getTotalCount(pageBean).intValue());
	}

	/**
	 * 添加或更新用户信息
	 * 添加时，添加用户信息和用户所属角色信息
	 * 修改时，只允许修改用户信息，不能修改角色信息
	 */
	@Override
	@Transactional(rollbackFor={Exception.class,RuntimeException.class})
	public void saveOrUpdateUser(User user,String[] roleID) {
		String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		if(user.getId()==null){
			//添加用户
			String salt = UUIDGenerator.getUUID(false);
			user.setSalt(salt);
			String password = EncryptionHelper.encrypt(user.getPassword(), salt);
			user.setPassword(password);			
			user.setCreateTime(time);
			user.setToken(UUIDGenerator.getUUID(false));
			user.setStatus(true);
			this.iUserMapper.saveUser(user);
			//添加角色
			if(roleID!=null && roleID.length>0){
				for (String rId : roleID) {
					this.iUserMapper.addUserRole(user.getId(), Integer.parseInt(rId),time);
				}
			}
			//默认添加用户为manager-管理员，3为manager的id
			//this.iUserMapper.addUserRole(user.getId(), 3,time);
			
		}else{
			User _user = this.iUserMapper.querUserByUserId(user.getId());
			if(!user.getPassword().equals(_user.getPassword())){
				//重新设置密码
				String salt = _user.getSalt();
				String password = EncryptionHelper.encrypt(user.getPassword(), salt);
				user.setPassword(password);
			}else{
				user.setPassword(_user.getPassword());
			}
			this.iUserMapper.updateUser(user);
			//更新角色
		/*	if(roleID!=null && roleID.length>0){
				
				
				//用户所有的角色集合
				List<UserRoleRelation> userRoleReList = this.iUserMapper.initUserRole(user.getId());
				List<Integer> userRoleList=new ArrayList<>();
				if(userRoleReList!=null && userRoleReList.size()>0){
					for (UserRoleRelation relation : userRoleReList) {
						userRoleList.add(relation.getRoleID());
					}
				}
				
				StringBuilder roleSb = new StringBuilder();
				for (int i = 0; i < roleID.length; i++) {
					//不包含角色
					if(!userRoleList.contains(roleID[i])){
						this.iUserMapper.addUserRole(user.getId(), Integer.parseInt(roleID[i]),time);
					}else{
					//包含角色
						roleSb.append(roleSb.toString().length() > 0 ? ","+roleID[i] : roleID[i]);
					}
				}
				
				if(roleSb!=null && roleSb.length()>0){
					//包含角色数组
					String[] rId = roleSb.toString().split(",");
					for (String s : rId) {
						if(userRoleList.contains(Integer.parseInt(s))){
							userRoleList.remove(Integer.valueOf(s));
						}
					}
				}
				
				for (Integer roleId : userRoleList) {
					this.iUserMapper.deleteUserRoleByUserIDAndRoleID(user.getId(), roleId);
				}
				
			}else{
				//删除用户所有角色
				this.iUserMapper.deleteAllUserRole(user.getId());
			}*/
			 
			
		}
	}
	/**
	 * 查询用户信息
	 */
	@Override
	public User querUserByUserId(Integer id) {
		return this.iUserMapper.querUserByUserId(id);
	}
	/**
	 * 查询用户的角色信息
	 */
	public List<UserRoleRelation> initUserRole(Integer userID){
		return this.iUserMapper.initUserRole(userID);
	}
	/**
	 * 设置用户状态
	 */
	@Override
	public void deleteById(Integer id,Integer status) {
		this.iUserMapper.deleteById(id,status);
	}

	/**
	 * 角色
	 */
	@Override
	public List<Role> initRole(){
		return this.iUserMapper.initRole();
	}
	/**
	 * 添加系统用户登录日志
	 */
	@Override
	public void addSysUserLogs(LoginLogs log) {
		this.iUserMapper.addSysUserLogs(log);
	}
	/**
	 * 修改用户状态
	 */
	@Override
	public void updateUserStatus(Integer id,Integer status){
		this.iUserMapper.updateUserStatus(id,status);
	}
}
